import modelExtend from 'dva-model-extend';
import pathToRegexp from 'path-to-regexp';
import base from './base';
import { statusOk } from '../utils/httpcode';
import { interact } from '../config/api';

export default modelExtend(base, {
  namespace: 'member',

  state: {
  },

  effects: {
    *join({ payload }, { call, put }) {
      const { params } = payload;

      const { code, message: result } = yield call(interact('joinMember'), params);
      const alertMessage = {
        title: code === statusOk ? '成功申请' : '申请失败',
        message: code === statusOk ? '您已成功申请入会, 请等候我们的审批通知' : result,
      };
      yield put({ type: 'alert', payload: alertMessage });
    },
    *updateMine({ payload }, { call, put }) {
      const { mine, success, error } = payload;

      const { code, message: result } = yield call(interact('updateMine'), mine);
      if (code !== statusOk) {
        if (typeof error === 'function') {
          error(result);
        } else {
          yield put({ type: 'alert', payload: { title: '错误', message: result } });
        }
        return undefined;
      }

      yield put({ type: 'syncState', payload: { mine } });

      if (typeof success === 'function') {
        success();
      }
    },
    *mineOnLoad(state, { call, put }) {
      const { mine } = state;
      if (mine) return undefined;

      const { code, message: result } = yield call(interact('getMine'));
      if (code !== statusOk) {
        yield put({ type: 'alert', payload: { title: '错误', message: result } });
        return undefined;
      }

      const { Member, ...rest } = result;
      yield put({
        type: 'syncState',
        payload: {
          mine: Member,
          ...rest,
        },
      });
    },
  },

  reducers: {
  },

  subscriptions: {
    setup({ history, dispatch }) {
      history.listen((location) => {
        let match = pathToRegexp('/mine').exec(location.pathname);
        if (match) {
          dispatch({ type: 'mineOnLoad' });
          return undefined;
        }

        match = pathToRegexp('/mine/detail').exec(location.pathname);
        if (match) {
          dispatch({ type: 'mineOnLoad' });
          return undefined;
        }
      });
    },
  },
});
